import { AuthContext } from '@/app/_layout';
import { deleteAllExcelFiles, deleteExcelFile, ExcelFileInfo, getAllExcelFiles, shareExcelFile } from '@/utils/excelGenerator';
import AsyncStorage from '@react-native-async-storage/async-storage';
import React, { useContext, useEffect, useState } from 'react';
import { Alert, FlatList, Modal, RefreshControl, StyleSheet, Text, TouchableOpacity, View } from 'react-native';

export default function ProfileScreen() {
  const [username, setUsername] = useState<string>('');
  const { setIsLogin } = useContext(AuthContext);
  const [excelFiles, setExcelFiles] = useState<ExcelFileInfo[]>([]);
  const [refreshing, setRefreshing] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedFile, setSelectedFile] = useState<ExcelFileInfo | null>(null);

  // 加载Excel文件列表
  const loadExcelFiles = async () => {
    try {
      const files = await getAllExcelFiles();
      setExcelFiles(files);
    } catch (error) {
      console.error('加载Excel文件列表失败:', error);
    }
  };

  // 刷新文件列表
  const onRefresh = async () => {
    setRefreshing(true);
    await loadExcelFiles();
    setRefreshing(false);
  };

  // 分享文件
  const handleShareFile = async (file: ExcelFileInfo) => {
    try {
      await shareExcelFile(file.date);
    } catch (error) {
      console.error('分享文件失败:', error);
      Alert.alert('错误', '分享文件失败，请重试');
    }
  };

  // 删除单个文件
  const handleDeleteFile = (file: ExcelFileInfo) => {
    setSelectedFile(file);
    setShowDeleteModal(true);
  };

  // 确认删除文件
  const confirmDeleteFile = async () => {
    if (!selectedFile) return;
    
    try {
      const success = await deleteExcelFile(selectedFile.date);
      if (success) {
        Alert.alert('成功', '文件已删除');
        await loadExcelFiles(); // 重新加载文件列表
      } else {
        Alert.alert('错误', '删除文件失败');
      }
    } catch (error) {
      console.error('删除文件失败:', error);
      Alert.alert('错误', '删除文件失败');
    } finally {
      setShowDeleteModal(false);
      setSelectedFile(null);
    }
  };

  // 删除所有文件
  const handleDeleteAllFiles = () => {
    Alert.alert(
      '确认删除',
      '确定要删除所有Excel文件吗？此操作不可恢复！',
      [
        { text: '取消', style: 'cancel' },
        {
          text: '确定',
          style: 'destructive',
          onPress: async () => {
            try {
              const result = await deleteAllExcelFiles();
              if (result.success > 0) {
                Alert.alert('成功', `已删除 ${result.success} 个文件`);
                await loadExcelFiles(); // 重新加载文件列表
              }
              if (result.failed > 0) {
                Alert.alert('部分失败', `${result.failed} 个文件删除失败`);
              }
            } catch (error) {
              console.error('删除所有文件失败:', error);
              Alert.alert('错误', '删除文件失败');
            }
          }
        }
      ]
    );
  };

  // 格式化文件大小
  const formatFileSize = (bytes?: number): string => {
    if (!bytes) return '未知大小';
    
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  // 格式化日期
  const formatDate = (dateStr: string): string => {
    const date = new Date(dateStr);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  // 渲染Excel文件项
  const renderExcelFileItem = ({ item }: { item: ExcelFileInfo }) => (
    <View style={styles.fileItem}>
      <View style={styles.fileInfo}>
        <Text style={styles.fileName}>{item.fileName}</Text>
        <Text style={styles.fileDate}>{formatDate(item.date)}</Text>
        <Text style={styles.fileSize}>{formatFileSize(item.size)}</Text>
      </View>
      <View style={styles.fileActions}>
        <TouchableOpacity
          style={[styles.actionButton, styles.shareButton]}
          onPress={() => handleShareFile(item)}
        >
          <Text style={styles.actionButtonText}>分享</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[styles.actionButton, styles.deleteButton]}
          onPress={() => handleDeleteFile(item)}
        >
          <Text style={styles.actionButtonText}>删除</Text>
        </TouchableOpacity>
      </View>
    </View>
  );

  useEffect(() => {
    // 假设用户名存储在 AsyncStorage 中，实际可根据项目调整
    AsyncStorage.getItem('NICK_NAME').then(name => {
      if (name) setUsername(name);
      else setUsername('未登录用户');
    });
    
    // 加载Excel文件列表
    loadExcelFiles();
  }, []);

  const handleLogout = async () => {
    Alert.alert('确认登出', '确定要退出登录吗？', [
      {
        text: '取消',
        style: 'cancel',
      },
      {
        text: '确定',
        style: 'destructive',
        onPress: async () => {
          await AsyncStorage.removeItem('ACCESS_TOKEN');
          await AsyncStorage.removeItem('REFRESH_TOKEN');
          await AsyncStorage.removeItem('NICK_NAME');
          setIsLogin(false);
        },
      },
    ]);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>我的信息</Text>
      <View style={styles.infoCard}>
        <Text style={styles.label}>用户名：</Text>
        <Text style={styles.value}>{username}</Text>
      </View>
      
      {/* Excel文件列表部分 */}
      <View style={styles.excelSection}>
        <View style={styles.sectionHeader}>
          <Text style={styles.sectionTitle}>Excel文件列表</Text>
          {excelFiles.length > 0 && (
            <TouchableOpacity
              style={styles.deleteAllButton}
              onPress={handleDeleteAllFiles}
            >
              <Text style={styles.deleteAllButtonText}>删除全部</Text>
            </TouchableOpacity>
          )}
        </View>
        
        {excelFiles.length === 0 ? (
          <View style={styles.emptyContainer}>
            <Text style={styles.emptyText}>暂无Excel文件</Text>
          </View>
        ) : (
          <FlatList
            data={excelFiles}
            renderItem={renderExcelFileItem}
            keyExtractor={(item) => item.date}
            style={styles.fileList}
            refreshControl={
              <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
            }
          />
        )}
      </View>
      
      <TouchableOpacity style={styles.logoutButton} onPress={handleLogout}>
        <Text style={styles.logoutButtonText}>退出登录</Text>
      </TouchableOpacity>
      
      {/* 删除确认模态框 */}
      <Modal
        animationType="fade"
        transparent={true}
        visible={showDeleteModal}
        onRequestClose={() => setShowDeleteModal(false)}
      >
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <Text style={styles.modalTitle}>确认删除</Text>
            <Text style={styles.modalMessage}>
              确定要删除文件 "{selectedFile?.fileName}" 吗？此操作不可恢复！
            </Text>
            <View style={styles.modalActions}>
              <TouchableOpacity
                style={[styles.modalButton, styles.cancelButton]}
                onPress={() => setShowDeleteModal(false)}
              >
                <Text style={styles.cancelButtonText}>取消</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[styles.modalButton, styles.confirmButton]}
                onPress={confirmDeleteFile}
              >
                <Text style={styles.confirmButtonText}>删除</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'flex-start', alignItems: 'center', backgroundColor: '#f5f7fa', padding: 20 },
  title: { fontSize: 28, fontWeight: 'bold', marginBottom: 20, color: '#0a7ea4' },
  infoCard: { backgroundColor: '#ffffff', borderRadius: 16, padding: 24, alignItems: 'center', marginBottom: 20, width: '100%', shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1, shadowRadius: 4, elevation: 3 },
  label: { fontSize: 18, color: '#333', marginBottom: 8 },
  value: { fontSize: 20, color: '#0a7ea4', fontWeight: 'bold' },
  logoutButton: { backgroundColor: '#e53935', borderRadius: 20, paddingVertical: 12, width: '60%', alignItems: 'center', marginTop: 20, marginBottom: 20 },
  logoutButtonText: { color: '#fff', fontSize: 18, fontWeight: 'bold' },
  
  // Excel文件列表样式
  excelSection: { backgroundColor: '#ffffff', borderRadius: 16, padding: 16, width: '100%', marginBottom: 20, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1, shadowRadius: 4, elevation: 3 },
  sectionHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 },
  sectionTitle: { fontSize: 20, fontWeight: 'bold', color: '#333' },
  deleteAllButton: { backgroundColor: '#ff5252', paddingHorizontal: 12, paddingVertical: 6, borderRadius: 12 },
  deleteAllButtonText: { color: '#ffffff', fontSize: 14, fontWeight: 'bold' },
  emptyContainer: { padding: 40, alignItems: 'center' },
  emptyText: { fontSize: 16, color: '#999' },
  fileList: { maxHeight: 300 },
  fileItem: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 12, borderBottomWidth: 1, borderBottomColor: '#f0f0f0' },
  fileInfo: { flex: 1 },
  fileName: { fontSize: 16, fontWeight: 'bold', color: '#333', marginBottom: 4 },
  fileDate: { fontSize: 14, color: '#666', marginBottom: 2 },
  fileSize: { fontSize: 12, color: '#999' },
  fileActions: { flexDirection: 'row' },
  actionButton: { paddingHorizontal: 12, paddingVertical: 6, borderRadius: 12, marginLeft: 8 },
  shareButton: { backgroundColor: '#4CAF50' },
  deleteButton: { backgroundColor: '#ff5252' },
  actionButtonText: { color: '#ffffff', fontSize: 12, fontWeight: 'bold' },
  
  // 模态框样式
  modalOverlay: { flex: 1, backgroundColor: 'rgba(0, 0, 0, 0.5)', justifyContent: 'center', alignItems: 'center' },
  modalContent: { backgroundColor: '#ffffff', borderRadius: 16, padding: 24, width: '80%', maxWidth: 300 },
  modalTitle: { fontSize: 20, fontWeight: 'bold', color: '#333', marginBottom: 16, textAlign: 'center' },
  modalMessage: { fontSize: 16, color: '#666', marginBottom: 24, textAlign: 'center' },
  modalActions: { flexDirection: 'row', justifyContent: 'space-around' },
  modalButton: { paddingHorizontal: 24, paddingVertical: 12, borderRadius: 24, minWidth: 100 },
  cancelButton: { backgroundColor: '#e0e0e0' },
  confirmButton: { backgroundColor: '#ff5252' },
  cancelButtonText: { color: '#333', fontSize: 16, fontWeight: 'bold', textAlign: 'center' },
  confirmButtonText: { color: '#ffffff', fontSize: 16, fontWeight: 'bold', textAlign: 'center' },
});
